package number_3;

import java.util.HashSet;
import java.util.Set;

public class Solution {

    //timeout;
    public int lengthOfLongestSubstring(String s) {
        int maxLen = Integer.MIN_VALUE;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j <= s.length(); j++) {
                if (singleton(s.substring(i, j))) {
                    maxLen = Math.max(maxLen, s.substring(i, j).length());
                }
            }
        }
        return maxLen == Integer.MIN_VALUE ? 0 : maxLen;
    }

    private boolean singleton(String s) {
        Set<Character> set = new HashSet<>();
        for (char c : s.toCharArray()) {
            if (set.contains(c)) {
                return false;
            }
            set.add(c);
        }
        return true;
    }

    public int lengthOfLongestSubstring1(String s) {
        int left = 0, right = 1;
        int maxLen = Integer.MIN_VALUE;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(s.charAt(left));
        while (right < s.length()) {
            int index;
            if ((index = stringBuilder.indexOf(String.valueOf(s.charAt(right)))) != -1) {
                maxLen = Math.max(maxLen, right - left);
                left = index + 1;
                while (index >= 0) {
                    stringBuilder.deleteCharAt(index--);
                }
            }
            stringBuilder.append(s.charAt(right));
            right++;
        }
        maxLen = Math.max(maxLen, right - left);
        return maxLen == Integer.MIN_VALUE ? 0 : maxLen;
    }

    public static void main(String[] args) {
        new Solution().lengthOfLongestSubstring1("abcabcbb");
    }
}
